package com.seven.netty.protocol.utils;

import com.seven.netty.protocol.bean.Body;
import com.seven.netty.protocol.bean.Message;
import com.seven.netty.protocol.constants.NettyConstant;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Map;

/**
 * @author chendongdong
 * @description byteBuf操作工具类
 * @since 2024/3/6 10:20
 */
@Slf4j
public class ByteUtil {
    /***
     * 对象数据 转 byte数组
     * @param obj
     * @return
     */
    public static byte[] toByteArray(Object obj) {
        if (obj == null) {
            return null;
        }
        byte[] result = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            result = bos.toByteArray();
            bos.close();
        } catch (IOException e) {
            log.error("数据转byte数组失败", e);
        }
        return result;
    }

    /***
     * byte数组转对象
     * @param obj
     * @return
     */
    public static Object byteToObject(byte[] obj) {
        if (obj == null || obj.length == 0) {
            return null;
        }
        Object result = null;
        ByteArrayInputStream bis = new ByteArrayInputStream(obj);
        try {
            ObjectInputStream ois = new ObjectInputStream(bis);
            result = ois.readObject();
            ois.close();
            bis.close();
        } catch (Exception e) {
            log.error("byte[]转对象数据失败", e);
        }
        return result;
    }

    /***
     * 计算数据长度
     * @param msg
     * @return
     */
    public static int calculateLength(Message msg) {
        int total = NettyConstant.HEAD_LENGTH + 2;
        Map<String, Object> attachment = msg.getHead().getAttachments();
        if (attachment != null && !attachment.isEmpty()) {
            for (Map.Entry<String, Object> entry : attachment.entrySet()) {
                int keylen = 4 + entry.getKey().length();
                Object value = entry.getValue();
                byte[] v = ByteUtil.toByteArray(value);
                total += keylen + 4 + v.length;
            }
        }
        Body body = msg.getBody();
        if (null != body) {
            Object payload = body.getPayload();
            byte[] data = ByteUtil.toByteArray(payload);
            if (data != null) {
                total += data.length;
            }
        }
        return total;
    }
}
